package com.bolt.support.freemarker;

import com.bolt.common.io.FileUtil;
import com.bolt.convention.exception.IORuntimeException;
import com.bolt.common.reflect.ClassUtil;
import com.bolt.convention.exception.ServiceException;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;

import java.io.IOException;

/**
 * Created by Administrator on 2020/10/13.
 */
public class FreeMarkerEngine implements TemplateEngine {

    private Configuration cfg;

    public FreeMarkerEngine(TemplateConfig config) {
        init(config);
    }

    /**
     * 使用指定配置文件初始化模板引擎
     *
     * @param config 配置文件
     * @return this
     */
    @Override
    public TemplateEngine init(TemplateConfig config) {
        cfg = new Configuration(Configuration.VERSION_2_3_25);
        cfg.setLocalizedLookup(false);
        cfg.setDefaultEncoding(config.getCharset().toString());
        cfg.setNumberFormat("###############");
        cfg.setBooleanFormat("true,false");
        cfg.setDefaultEncoding("UTF-8");
        switch (config.getResourceMode()) {
            case CLASSPATH:
                cfg.setTemplateLoader(new ClassTemplateLoader(ClassUtil.getClassLoader(), config.getPath()));
                break;
            case FILE:
                try {
                    cfg.setTemplateLoader(new FileTemplateLoader(FileUtil.file(config.getPath())));
                } catch (IOException e) {
                    throw new IORuntimeException(e);
                }
                break;
            case WEB_ROOT:
                try {
                    cfg.setTemplateLoader(new FileTemplateLoader(FileUtil.file(FileUtil.getWebRoot(), config.getPath())));
                } catch (IOException e) {
                    throw new IORuntimeException(e);
                }
                break;
            case STRING:
                cfg.setTemplateLoader(new StringTemplateLoader());
                break;
            default:
                break;
        }
        return this;
    }

    /**
     * 获取模板
     *
     * @param resource 资源，根据实现不同，此资源可以是模板本身，也可以是模板的相对路径
     * @return 模板实现
     */
    @Override
    public Template getTemplate(String resource) {
        if (null == this.cfg) {
            throw new ServiceException("配置不完善!");
        }
        try {
            return FreeMarkerTemplate.wrap(this.cfg.getTemplate(resource));
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

}

 